package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
//        Employee employee = employeeMapper.getByUsername(username);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, username);
        Employee employee = employeeMapper.selectOne(qw);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 将前端传来的明文密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
//        log.info("当前线程id：{}", Thread.currentThread().getId());

        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账户状态
        employee.setStatus(StatusConstant.ENABLE);

        //设置创建时间和更新时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //设置当前记录的创建者id和更新者id
        //  todo 暂时使用假数据，后期更改为当前登录的用户id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        //设置默认密码 123456
        employee.setPassword(DigestUtils
                .md5DigestAsHex(
                        PasswordConstant.DEFAULT_PASSWORD
                                .getBytes()));

        employeeMapper.insert(employee);
    }


    @Override
    public PageResult getEmpsByPage(EmployeePageQueryDTO employeePageQueryDTO) {
        int page = employeePageQueryDTO.getPage();
        int pageSize = employeePageQueryDTO.getPageSize();

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeePageQueryDTO, employee);

        Page<Employee> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotBlank(employee.getName()), Employee::getName, employee.getName())
                .orderByDesc(Employee::getUpdateTime);
        employeeMapper.selectPage(pageInfo, qw);

        // 使用构造器引用创建PageResult对象并返回
        return new PageResult(pageInfo.getTotal(), pageInfo.getRecords());
    }

    @Override
    public void updateStatus(Integer status, long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();
        employeeMapper.updateById(employee);
    }

    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {

        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();
        //md5加密
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());


        Long empId = passwordEditDTO.getEmpId();//前端代码传回数据为 empId=null
        Long currentId = BaseContext.getCurrentId();//获取当前登录的账号id

        empId = currentId;


        Employee employee = Employee.builder()
                .id(empId)
                .password(newPassword)
                .build();

        Employee employee1 = this.getById(empId);
        if (employee1 != null) {
            //数据库查询到的对应密码
            String initPassword = employee1.getPassword();


            // 检查输入的旧密码是否与数据库原始密码相同
            if (initPassword != null && initPassword.equals(oldPassword)) {
                // 旧密码输入正确，检查输入的旧密码与新密码是否相同
                if (oldPassword.equals(newPassword)) {
                    // 如果新旧密码一致，不执行修改密码的逻辑，可以返回提示或报错
                    // 新旧密码一致的处理逻辑
                    throw new PasswordEditFailedException(
                            MessageConstant.THE_OLD_AND_NEW_PASSWORDS_ARE_THE_SAME);
                } else {
                    // 新旧密码不一致，可以继续执行修改密码的逻辑
                    // 修改密码的代码
                    log.info("密码修改成功...");
                    this.updateById(employee);
                    return;
                }
            } else {
                // 旧密码不匹配，返回错误或报错
                // 在这里添加密码不匹配的处理逻辑
                throw new PasswordEditFailedException(
                        MessageConstant.OLD_PASSWORD_IS_WRONG);
            }
        } else {
            // 根据 empId 未找到员工记录，返回错误或报错
            // 在这里添加未找到员工记录的处理逻辑
            throw new PasswordErrorException(
                    MessageConstant.ACCOUNT_NOT_FOUND);
        }

    }

}
